package com.jingzhi.count.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * 作者： 张恒同
 * 时间：2018/3/23   14:02
 * 描述：
 */
public class JsonUtil {

    private static ObjectMapper        mapper;

    public static void initMapper() {
        if (mapper == null) {
            synchronized (JsonUtil.class){
                if (mapper == null){
                    mapper = new ObjectMapper();
                    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
                    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
                }
            }
        }
    }

    /**
     *  json 转bean
     *
     *  @param json
     *  @param clss
     *  @return T
     * */
    public static <T> T jsonToBean(String json, Class<T> clss){
        initMapper();
        try {
            return mapper.readValue(json, clss);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *  实体类转json字符串
     *
     *  @param obj
     *  @return String
     * */
    public static String beanToJson(Object obj){
        initMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    

}
